import 'dart:convert';
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:convert/convert.dart';
import 'package:crypto/crypto.dart';
import 'dart:async';
import 'package:flutter/cupertino.dart';
import 'package:package_info/package_info.dart';
import 'package:device_info/device_info.dart';
import 'package:riki_login/api/oauth/oauth_api.dart';
import 'package:riki_login/config/global.dart';
import 'package:riki_login/res/header.dart';

///作者：范玉辉
///创建时间：2020/12/16
///说明：密码登录数据管理

class UserLoginPasswordViewModel extends SingleViewStateModel {
  late UserPassLoginApi passLoginApi; // 密码登录
  late UserLoginRecordApi _userLoginRecordApi; // 告诉后台登陆成功
  String userPhone = ''; //手机号
  String userPassword = '';

  // 埋点
  late Map<String, dynamic> param;

  ///初始化api
  void initApi(BuildContext context) {
    passLoginApi = UserPassLoginApi(context);
    _userLoginRecordApi = UserLoginRecordApi(context);
  }

  ///密码登录
  Future passLogin(BuildContext context) async {
    Completer completer = Completer();
    String devicedInfo = await getDeviceInfo();
    String versionInfo = await getVersionInfo();

    passLoginApi.start(params: {
      "phone": userPhone.trim(), //手机号
      "password": generateMd5(userPassword.trim()),
      "type": getSendPlatformType(), //哪个端 1:ios 2:安卓
      "deviceId": devicedInfo, //设备的id
      "version": versionInfo,
      "clientType": getSendPlatformType() //客户端类型 1:ios 2:安卓
    }).then((res) {
      if (res.success??false) {
        //替换为上面的方法
        if (res.result != null) {
          RikiLoginGlobal.saveUserAccount(res.result);
          RikiLogin.instance.refreshUserLoginEntity(res.result!);
          RikiBase.setAccessToken(res.result!.accessToken!);
          Future.delayed(const Duration(seconds: 1), () {
            _userLoginRecord();
            ToastUtil.showPositiveToast('登录成功');
            completer.complete();
          });
        }
      } else {
        if (res.statusCode == 3602) {
          // 登陆过期
          RikiLogin.instance.onLoginDateCallback(context);
        } else {
          ToastUtil.showNegativeToast(res.message);
        }
        completer.complete();
      }
    });
    return completer.future;
  }

  //获取设备信息
  Future<String> getDeviceInfo() async {
    DeviceInfoPlugin deviceInfo = new DeviceInfoPlugin();
    if (Platform.isAndroid) {
      AndroidDeviceInfo androidInfo = await deviceInfo.androidInfo;
      return androidInfo.id;
    } else if (Platform.isIOS) {
      IosDeviceInfo iosInfo = await deviceInfo.iosInfo;
      return iosInfo.identifierForVendor;
    } else {
      return '';
    }
  }

  //获取哪个平台
  int getSendPlatformType() {
    return Platform.isAndroid ? 2 : 1;
  }

  //获取版本号
  Future<String> getVersionInfo() async {
    PackageInfo packageInfo = await PackageInfo.fromPlatform();
    return packageInfo.version;
  }

  // md5 加密
  String generateMd5(String data) {
    var content = new Utf8Encoder().convert(data);
    var digest = md5.convert(content);
    // 这里其实就是 digest.toString()
    return hex.encode(digest.bytes);
  }

  /// 告诉后台登录成功
  Future _userLoginRecord() async {
    _userLoginRecordApi.start(params: {}).then((res) {});
  }

  @override
  void dispose() {
    super.dispose();
    passLoginApi.cancel();
  }

  @override
  Future loadData() {
    throw UnimplementedError();
  }

  @override
  onCompleted(data) {
    throw UnimplementedError();
  }
}
